package com.aiti.lulian.controller;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.ShowEnterpriseServiceDto;
import com.aiti.lulian.entity.MyCollection;
import com.aiti.lulian.entity.ShowEnterpriseServiceEntity;
import com.aiti.lulian.entity.ShowServiceEnterprise;
import com.aiti.lulian.entity.excel.ShowEnterpriseServiceEntityExport;
import com.aiti.lulian.handler.HeaderStyleHandler;
import com.aiti.lulian.service.IMyCollectionService;
import com.aiti.lulian.service.IShowEnterpriseServiceService;
import com.aiti.lulian.service.ShowServiceEnterpriseService;
import com.aiti.lulian.vo.EmployeeOpportunityCountVo;
import com.aiti.lulian.vo.ShowEnterpriseServiceVo;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务 前端控制器
 * </p>
 *
 * @author 
 * @since 2025-06-11
 */
@RestController
@RequestMapping("/service")
@Slf4j
public class ShowEnterpriseServiceController extends WebController {

    @Autowired
    private IShowEnterpriseServiceService enterpriseServiceService;
    @Autowired
    private ShowServiceEnterpriseService serviceEnterpriseService;
    @Autowired
    private IMyCollectionService myCollectionService;



    @GetMapping("/page")
    public Message page(ShowEnterpriseServiceDto dto){
        Integer pageSize = dto.getPageSize();
        Integer pageNum = dto.getPageNum();
        if (StrUtil.isBlank(dto.getUserId())) {
            dto.setUserId(findUserId());
            if (StrUtil.isBlank(dto.getUserId())) {
                return Fail("请先登录");
            }
        }
        Page<EmployeeOpportunityCountVo> page = this.startPage(pageNum, pageSize);
        List<ShowEnterpriseServiceVo> list = enterpriseServiceService.serviceList(page, dto);
        return Message.success(getPageResult(list,pageNum, pageSize, (int)page.getTotal()));
    }

    @GetMapping("/detail")
    public Message detail(ShowEnterpriseServiceDto dto){
        ShowEnterpriseServiceEntity entity = enterpriseServiceService.getById(dto.getBaseId());
        String loginUserId = findUserId();
        if(StrUtil.isNotEmpty(loginUserId)) {
            enterpriseServiceService.setDetailInfo(entity, findUserId());
        }
        return Message.success(entity);
    }

    @DeleteMapping
    public Message delete(ShowEnterpriseServiceDto dto){
        String baseId = dto.getBaseId();
        if(StrUtil.isNotBlank(baseId)){
            enterpriseServiceService.removeById(baseId);
            // 删除该服务绑定的服务商用户及用户的角色
            enterpriseServiceService.removeServerUser(baseId);
            return Message.success();
        }else{
            return Message.fail("传参有误");
        }
    }

    @ApiOperation("删除商品绑定的服务商用户")
    @DeleteMapping("/delServerUser")
    public Message deleteServerUser(@RequestParam("username") String username,
                                    @RequestParam("fundBaseId") String fundBaseId) {
        try {
            enterpriseServiceService.deleteServerUser(username, fundBaseId);
            return Message.success();
        }catch (Exception e) {
            if(e instanceof BusinessException) {
                return Message.fail(e.getMessage());
            }
            log.error("删除服务商用户异常：{}", ExceptionUtil.stacktraceToString(e));
            return Message.fail("接口异常："+ e.getMessage());
        }
    }

    @PostMapping
    public Message insert(@RequestBody ShowEnterpriseServiceEntity entity){
        ShowServiceEnterprise serviceEnterprise = serviceEnterpriseService.getById(entity.getEnterpriseId());
        if (StrUtil.isBlank(serviceEnterprise.getLogo())) {
            return Message.fail("请先上传企业LOGO");
        }
        entity.setCreator(findUserId());
        fillEnterprise(entity);
        enterpriseServiceService.save(entity);
        enterpriseServiceService.addServerUser(entity, serviceEnterprise, findUserId());
        return Message.success();
    }

    @PutMapping
    public Message update(@RequestBody ShowEnterpriseServiceEntity entity){
        entity.setUpdateBy(findUserId());
        fillEnterprise(entity);
        enterpriseServiceService.updateById(entity);
        // 更新收藏表
        List<MyCollection> collections = myCollectionService.list(new LambdaQueryWrapper<MyCollection>().eq(MyCollection::getModule, "1").eq(MyCollection::getId, entity.getBaseId()));
        List<String> collectionIds = collections.stream().map(MyCollection::getBaseId).collect(Collectors.toList());
        if (collections.size() > 0) {
            myCollectionService.update(new LambdaUpdateWrapper<MyCollection>().in(MyCollection::getBaseId, collectionIds).set(MyCollection::getType, entity.getServiceType()));
        }
        ShowServiceEnterprise serviceEnterprise = serviceEnterpriseService.getById(entity.getEnterpriseId());
        enterpriseServiceService.addServerUser(entity, serviceEnterprise, findUserId());
        return Message.success();
    }

    @PutMapping("/add")
    public Message addCount(@RequestBody ShowEnterpriseServiceDto dto){
        return enterpriseServiceService.addCount(dto);
    }

    private void fillEnterprise(ShowEnterpriseServiceEntity entity){
        String enterpriseId = entity.getEnterpriseId();
        ShowServiceEnterprise serviceEnterprise = serviceEnterpriseService.getById(enterpriseId);
        entity.setProvince(serviceEnterprise.getProvince());
        entity.setCity(serviceEnterprise.getCity());
        entity.setCounty(serviceEnterprise.getCounty());
        entity.setStreet(serviceEnterprise.getStreet());
        entity.setTelephone(serviceEnterprise.getTelephone());
        entity.setLogo(serviceEnterprise.getLogo());
        entity.setAddress(serviceEnterprise.getAddress());
        entity.setEnterpriseName(serviceEnterprise.getBaseName());
    }

    @ApiOperation("下载服务导入模版")
    @GetMapping("/importTemplate/download")
    public void downloadEnterpriseServiceImportTemplate(HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        ServletOutputStream outputStream = null;
        try {
            // 设置文件路径
//            String filePath = "/Volumes/WorkDisk/ShanDongZhiZao/workspace/template/工信门户-服务导入模版.xlsx";
            String filePath = "/home/services/template/工信门户-服务导入模版.xlsx";
//            String filePath = "C:\\Users\\Administrator\\Desktop\\工信门户-服务导入模版.xlsx;
            File downloadFile = new File(filePath);

            // 设置文件名（响应头中的推荐文件名）
            String fileName = "服务导入模版.xlsx";

            // 对文件名进行URL编码
            String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");

            // 设置响应头
            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"; filename*=UTF-8''" + encodedFileName);

            // 设置文件大小
            response.setContentLength((int) downloadFile.length());

            // 通过文件输入流读取文件内容
            fileInputStream = new FileInputStream(downloadFile);

            // 通过ServletOutputStream将文件内容写入HTTP响应
            outputStream = response.getOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            // 关闭流资源
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (Exception e) {
            logger.error("下载服务导入模版异常：===》" + e);
        }
    }

    @ApiOperation("批量导入服务")
    @PostMapping("/importBatch")
    public Message importEnterpriseServiceBatch(@RequestPart("file") MultipartFile file) {
        try {
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                return Fail("请先登录");
            }
            if (file == null) {
                return Fail("请上传文件");
            }
            String contentType = file.getContentType();
            String originalFilename = file.getOriginalFilename();
            if (! ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equals(contentType)
                    && originalFilename != null && originalFilename.endsWith(".xlsx"))) {
                return Fail("请上传xlsx格式的文件");
            }
            return enterpriseServiceService.importBatch(file, userId);
        } catch (Exception e) {
            logger.error("导入异常：===》" + e);
            return Fail(e.getMessage());
        }
    }

    @ApiOperation("导出服务列表")
    @GetMapping("/list/export")
    public Message exportEnterpriseServiceList(HttpServletResponse response, ShowEnterpriseServiceDto dto) {
        try {
            dto.setUserId(findUserId());
            List<ShowEnterpriseServiceVo> list = enterpriseServiceService.serviceList(null, dto);
            List<ShowEnterpriseServiceEntityExport> enterpriseServiceExportList = list.stream().map(i -> {
                ShowEnterpriseServiceEntityExport enterpriseServiceExport = new ShowEnterpriseServiceEntityExport();
                BeanUtils.copyProperties(i, enterpriseServiceExport);
                return enterpriseServiceExport;
            }).collect(Collectors.toList());

            // 设置响应头，确保浏览器以下载方式处理文件
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");

            // 设置文件名，注意需要对中文进行 URL 编码
            String fileName = URLEncoder.encode("服务列表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=\"" + fileName + ".xlsx\";" +
                            " filename*=UTF-8''" + fileName + ".xlsx");

            // 使用 EasyExcel 写入数据到输出流
            OutputStream outputStream =  response.getOutputStream();
            EasyExcel.write(outputStream, ShowEnterpriseServiceEntityExport.class)
                    .sheet("服务列表")
                    .registerWriteHandler(new HeaderStyleHandler())
                    .doWrite(enterpriseServiceExportList);

            // 关闭流资源
            if (outputStream != null) {
                outputStream.close();
            }

            return Message.success();
        } catch (Exception e) {
            logger.error("导出异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }
}
